package com.scut.online_black_market.controller;

import com.alibaba.fastjson.JSON;
import com.scut.online_black_market.dto.MessageInfo;
import com.scut.online_black_market.utility.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
public class CommunicationController {

    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;

    @Resource
    private HttpServletRequest request;

    @Resource
    private JwtUtil jwtUtil;

    @MessageMapping("/service/communication")
    @Async("communication-thread-pool")
    public void communication(@Payload String body) {
        MessageInfo messageInfo = JSON.parseObject(body, MessageInfo.class);
        log.info("收到用户 " + jwtUtil.extractStudentNumber(request) + " 发给用户 " + messageInfo.getToStudentNumber() + " 的消息，消息内容：" + messageInfo.getMessage());
        MessageInfo build = MessageInfo.builder()
                .message(messageInfo.getMessage())
                .toStudentNumber(jwtUtil.extractStudentNumber(request))
                .build();
        simpMessagingTemplate.convertAndSend("/service/notify/" + messageInfo.getToStudentNumber(), build);

    }
}
